/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pessoas.exportacaoXml;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/**
 *
 * @author Bush
 */
public class ExportaXml {

    public ExportaXml() {
    }    
    
    public void gravaXMLContatos(ArrayList lista, String caminho) throws IOException, Exception {
        XStream parser = new XStream(new DomDriver());
        parser.setMode(XStream.NO_REFERENCES);
        String xml = parser.toXML(lista);
        limpaGravaXMLContatos(tratamentoExportacao(xml), caminho);
    }

    public void limpaGravaXMLContatos(String xml, String caminho) throws FileNotFoundException, IOException, Exception {
        FileWriter w = new FileWriter(caminho, false);
        BufferedWriter bf = new BufferedWriter(w);
        long inicio = System.currentTimeMillis();
        bf.write(xml);
        long fim = System.currentTimeMillis();
        if(fim - inicio > 5000){
            throw new Exception("Excedeu tempo limite de Exportação");
        }
        bf.close();
    }
    
    public String tratamentoExportacao(String linha) {

        linha = linha.replace("<list>", "<contatos>");
        linha = linha.replace("</list>", "</contatos>");
        linha = linha.replace("<pessoas.model.Contato>", "<contato>");
        linha = linha.replace("</pessoas.model.Contato>", "</contato>");
        return linha;
    }
}
